/*
 Lembrete, estou usando Espaçamento de [Nome] 1L [Campo]
 Altura entre objetos 2L

 String CadastroN = Pattern.compile("[^0-9]").matcher(jCadastroN.getText()).replaceAll("");
 clientes.setIdclientes(Integer.parseInt(CadastroN));

 Retorna true se a String passada contiver apenas caracteres numericos   
 private boolean campoNumerico(String campo) {
 return campo.matches("[0-9]+");
 }
 */
package br.com.softbook.view;

import br.com.softbook.bean.Cadastroclientes;
import br.com.softbook.bean.Cidades;
import br.com.softbook.util.HibernateUtil;
import java.awt.Font;
import java.text.ParseException;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import org.hibernate.Session;
import br.com.softbook.util.FixedLengthDocument;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Query;
import static org.hibernate.util.StringHelper.toUpperCase;

/**
 *
 * @author OzY
 */
public class formCadastroClientes extends javax.swing.JFrame {

    /**
     * Creates new form formCadastroClientes
     */
    public formCadastroClientes() {
        //[INICIO]Look And Feell 
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");// Captura Estilo do S.O
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //[FIM]Look And Feell 
        initComponents();
        this.setLocationRelativeTo(this);//Centralizar FORM
        delimitadorCaracters();
        DisableOption();//Desabilitar opcoes de inicializacao.
        idGenerator();//Gerador de ID

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jNomeC = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jEndereco = new javax.swing.JTextField();
        jCCidade = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jTelefone = new javax.swing.JFormattedTextField();
        optionCpf = new javax.swing.JRadioButton();
        optionCnpj = new javax.swing.JRadioButton();
        jLabelCpfCnpj = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jCnpjCpf = new javax.swing.JFormattedTextField();
        jButton2 = new javax.swing.JButton();
        jRG = new javax.swing.JFormattedTextField();
        jCadastroN = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jTConsulta = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel1.setText("Cadastro Nº:");

        jLabel2.setText("Nome Completo:");

        jNomeC.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jNomeCFocusLost(evt);
            }
        });

        jLabel5.setText("RG Nº:");

        jLabel6.setText("Endereço:");

        jCCidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", " " }));

        jLabel7.setText("Cidade:");

        jLabel8.setText("Telefone Nº:");

        try {
            jTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        buttonGroup1.add(optionCpf);
        optionCpf.setText("Pessoa Física");
        optionCpf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optionCpfActionPerformed(evt);
            }
        });

        buttonGroup1.add(optionCnpj);
        optionCnpj.setText("Pessoa Jurídica");
        optionCnpj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optionCnpjActionPerformed(evt);
            }
        });

        jLabelCpfCnpj.setText("CPF Nº:");

        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Sair");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        try {
            jRG.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jCadastroN.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jCadastroNFocusLost(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(104, 104, 104)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabelCpfCnpj, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jNomeC, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jEndereco)
                                .addComponent(jTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jCCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jCnpjCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jRG, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCadastroN, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(127, Short.MAX_VALUE)
                .addComponent(optionCpf)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(optionCnpj)
                .addGap(123, 123, 123))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(optionCpf)
                    .addComponent(optionCnpj))
                .addGap(50, 50, 50)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jCadastroN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jNomeC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jRG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelCpfCnpj)
                    .addComponent(jCnpjCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(53, 53, 53))
        );

        jTabbedPane2.addTab("Cadastro de Clientes", jPanel4);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jTConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTConsultaKeyReleased(evt);
            }
        });

        jLabel3.setText("Informe a busca:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jTConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(381, 381, 381))
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome", "Tipo", "Endereço", "Telefone"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane2.addTab("Consulta", jPanel2);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 449, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 1, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane2)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void optionCpfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optionCpfActionPerformed
        verificaSelecionado();
    }//GEN-LAST:event_optionCpfActionPerformed

    private void optionCnpjActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optionCnpjActionPerformed
        verificaSelecionado();
    }//GEN-LAST:event_optionCnpjActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Cadastroclientes clientes = new Cadastroclientes();

        clientes.setIdclientes(Integer.parseInt(jCadastroN.getText()));

        clientes.setClientesnome(jNomeC.getText());
        clientes.setClientesendereco(jEndereco.getText());

        Cidades city = new Cidades();
        city.setIdcidades(jCCidade.getSelectedIndex() + 1);
        clientes.setCidades(city);

        clientes.setClientestelefone(jTelefone.getText());
        clientes.setClientesrg(jRG.getText());
        clientes.setClientescpfcnpj(jCnpjCpf.getText());
        if (optionCnpj.isSelected()) {
            clientes.setClientestipo("Jurídica");
        } else {
            clientes.setClientestipo("Física");
        }

        if (jNomeC.getText().trim().equals("") || jEndereco.getText().trim().equals("") || jEndereco.getText() == null || jNomeC.getText() == null || jCnpjCpf.getText().trim().equals("") || jCnpjCpf.getText() == null || jRG.getText().equals("") || jRG.getText() == null) {
            JOptionPane.showMessageDialog(null, "Verfique os campos digitados!");
            jNomeC.requestFocus();
        } else {
            //Commit no banco de dados.
            Session session = HibernateUtil.getSession();
            session.beginTransaction();
            session.saveOrUpdate(clientes);
            session.flush();
            session.getTransaction().commit();
            JOptionPane.showMessageDialog(null, "Cadastrado com Sucesso!");
            jNomeC.requestFocus();

            limpacampo();
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jCadastroNFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jCadastroNFocusLost
//        if (campoNumerico(jCadastroN.getText()) == false) {
//            jLabel1.setFont(new Font("Tahoma", Font.BOLD, 11));
//            JOptionPane.showMessageDialog(null, "Campo vazio ou com letras!");
//            jCadastroN.setText(null);
//            jCadastroN.requestFocus();
//        } else {
//            jLabel1.setFont(new Font("Tahoma", Font.PLAIN, 11));
//        }
    }//GEN-LAST:event_jCadastroNFocusLost

    private void jTConsultaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTConsultaKeyReleased
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);
        buscarPorNome(jTConsulta.getText());
        List<Cadastroclientes> list = buscarPorNome(jTConsulta.getText());
        for (Cadastroclientes c : list) {
            modelo.addRow(new Object[]{
                c.getClientesnome(), c.getClientestipo(), c.getClientesendereco(), c.getClientestelefone()});
        }

    }//GEN-LAST:event_jTConsultaKeyReleased

    private void jNomeCFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jNomeCFocusLost
        Session session = HibernateUtil.getSession();
        List<Cadastroclientes> lista = session.createCriteria(Cadastroclientes.class).list();
        for (Cadastroclientes c : lista) {
            if(c.getClientesnome().equals(jNomeC.getText()) || c.getClientesnome().equals(toUpperCase(jNomeC.getText()))){
                JOptionPane.showMessageDialog(null, "O usuario já existe!");
                jTConsulta.requestFocus();
                jTabbedPane2.setSelectedIndex(1);
            }
        }
        session.flush();
        session.close();
//
    }//GEN-LAST:event_jNomeCFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(formCadastroClientes.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(formCadastroClientes.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(formCadastroClientes.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(formCadastroClientes.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new formCadastroClientes().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jCCidade;
    private javax.swing.JTextField jCadastroN;
    private javax.swing.JFormattedTextField jCnpjCpf;
    private javax.swing.JTextField jEndereco;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabelCpfCnpj;
    private javax.swing.JTextField jNomeC;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JFormattedTextField jRG;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTConsulta;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JFormattedTextField jTelefone;
    private javax.swing.JRadioButton optionCnpj;
    private javax.swing.JRadioButton optionCpf;
    // End of variables declaration//GEN-END:variables

//Desabilitar opções
    public void DisableOption() {
        jNomeC.setEnabled(false);
        jCadastroN.setEnabled(false);
        jEndereco.setEnabled(false);
        jTelefone.setEnabled(false);
        jRG.setEnabled(false);
        jCnpjCpf.setEnabled(false);
        jCCidade.setEnabled(false);
    }
// Limpar campos

    public void limpacampo() {
        jNomeC.setText(null);
        jEndereco.setText(null);
        jTelefone.setText(null);
        jRG.setText(null);
        jCnpjCpf.setText(null);
        jCCidade.setSelectedItem(null);
        idGenerator();
        jButton1.setEnabled(true);
    }
//aqui verifica qual JRadioButton foi marcado e seto a mascara no campo cnpjCpf q e um JFormattedTextField

    public void verificaSelecionado() {
        MaskFormatter formatter = null;
        try {
            jCnpjCpf.setValue(null);
            if (optionCnpj.isSelected()) {
                PreencherCombo();
                jNomeC.requestFocus();
                jNomeC.setEnabled(true);
                jButton1.setEnabled(true);
                jEndereco.setEnabled(true);
                jTelefone.setEnabled(true);
                jRG.setEnabled(true);
                jCnpjCpf.setEnabled(true);
                jCCidade.setEnabled(true);
                formatter = new MaskFormatter("##.###.###/####-##");
                formatter.setPlaceholderCharacter(' ');
                jCnpjCpf.setFormatterFactory(new DefaultFormatterFactory(formatter));
                jLabelCpfCnpj.setText("CNPJ Nº:");
                optionCnpj.setFont(new Font("Tahoma", Font.BOLD, 11));
                optionCpf.setFont(new Font("Tahoma", Font.PLAIN, 11));

            } else {
                PreencherCombo();
                jNomeC.requestFocus();
                jNomeC.setEnabled(true);
                jButton1.setEnabled(true);
                jEndereco.setEnabled(true);
                jTelefone.setEnabled(true);
                jRG.setEnabled(true);
                jCnpjCpf.setEnabled(true);
                jCCidade.setEnabled(true);
                formatter = new MaskFormatter("###.###.###-##");
                formatter.setPlaceholderCharacter(' ');
                jCnpjCpf.setFormatterFactory(new DefaultFormatterFactory(formatter));
                jLabelCpfCnpj.setText("CPF Nº:");
                optionCpf.setFont(new Font("Tahoma", Font.BOLD, 11));
                optionCnpj.setFont(new Font("Tahoma", Font.PLAIN, 11));
            }

        } catch (ParseException ex) {
            ex.printStackTrace();
        }
    }
    //Preencher combo com as informações contidas no Banco de Dados!

    public void PreencherCombo() {
        Session session = HibernateUtil.getSession();
        jCCidade.removeAllItems();
        List<Cidades> lista = session.createCriteria(Cidades.class
                ).list();
        for (Cidades c : lista) {
            jCCidade.addItem(c.getIdcidadesdescricao());
        }
        session.flush();
        session.close();

    }

// Delimita o do Label, passando por parametro um valor
    public void delimitadorCaracters() {
        jNomeC.setDocument(new FixedLengthDocument(30));
        jEndereco.setDocument(new FixedLengthDocument(30));
    }

    //Gerador Automatico de ID.
    private void idGenerator() {
        jCadastroN.setEnabled(false);
        jButton1.setEnabled(false);
        int i = 1;
        Session session = HibernateUtil.getSession();
        List<Cadastroclientes> lista = session.createCriteria(Cadastroclientes.class
                ).list();// Irá fazer uma Lista
        for (Cadastroclientes cadCli : lista) {
            i++;
        }
        jCadastroN.setText(Integer.toString(i));
    }

    public List<Cadastroclientes> buscarPorNome(String nome) {
        Session session = HibernateUtil.getSession();
        Query q = session.createQuery("from Cadastroclientes C where CLIENTESNOME like ?");
        q.setString(0, "%" + nome + "%");
        return q.list();
    }
}
